#include <stdio.h>

void find_min_k(int arr[], int lo, int hi, int k)
{
    if (k == 0) {
        return;
    }

    int i = lo - 1, j = hi;

    while (i < j) {
        while (arr[++i] < arr[hi]);

        while (arr[--j] > arr[hi]) {
            if (j == lo) {
                break;
            }
        }

        if (i >= j) {
            break;
        }

        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    int tmp = arr[hi];
    arr[hi] = arr[i];
    arr[i] = tmp;

    int cnt = i - lo + 1;

    if (cnt < k) {
        find_min_k(arr, i + 1, hi, k - cnt);
    } else if (cnt > k) {
        find_min_k(arr, lo, i - 1, k);
    } else {
        return;
    }
}

int main(int argc, const char *argv[])
{
    int arr[] = {5, 1, 3, 6, 7, 2, 8, 4};

    for (int i = 0; i < sizeof(arr) / sizeof(arr[0]) - 1; ++i) {
        printf("%d ", arr[i]);
    }

    find_min_k(arr, 0, sizeof(arr) / sizeof(arr[0]) - 1, 4);
    printf("\n");

    for (int i = 0; i < 4; ++i) {
        printf("%d ", arr[i]);
    }

    printf("\n");
    return 0;
}
